package Server.Chat;

import Protobuf.ChatProto;
import Protobuf.DbProto;
import Server.Cache.MsgSession;
import Server.Cache.PlayerCache;
import Server.Common.Player;
import Server.Common.World;
import Server.DbClientHandler;
import io.netty.channel.Channel;

public class PrivateChat implements Chat {

    @Override
    public void sendPacket(MsgSession session) {
        ChatProto.Msg sendPri;
        ChatProto.Msg msg = session.getMsg();
        Player sender = PlayerCache.getInstance().getPlayer(msg.getChat().getSenderId());
        //玩家不存在
        ChatProto.Chat priChat = msg.getChat();
        System.out.println(msg.getChat().getReceiver()+" "+World.getInstance().allId.contains(priChat.getReceiver()));
        if(!World.getInstance().allId.contains(priChat.getReceiver())){
            sendPri = ChatProto.Msg.newBuilder().setMsgType(msg.getMsgType())
                    .setRespChat(ChatProto.RespChat.newBuilder().setChatResult(ChatProto.RespChat.ChatResult.idIneffective).build()).build();
            sender.sendMsg(sendPri);
        }else {
            String channelId = session.getChannelId();
            sendPri  = ChatProto.Msg.newBuilder().setMsgType(msg.getMsgType())
                    .setRespChat(ChatProto.RespChat.newBuilder().setSender(priChat.getSenderName()).setMsg(priChat.getMsg()).build()).build();
            sender.sendMsg(sendPri);
            //如果接收私聊玩家在线，发送私聊
            if (PlayerCache.getInstance().isContainsPlayer(priChat.getReceiver())) {
                PlayerCache.getInstance().getPlayer(priChat.getReceiver()).sendMsg(sendPri);
            }
            DbProto.Msg sendPriMsg = DbProto.Msg.newBuilder().setMsgType(DbProto.Msg.MsgType.priChat).setChannelId(channelId)
                    .setChatMsg(DbProto.ChatMsg.newBuilder().setSenderId(priChat.getSenderId())
                            .setReceiverId(priChat.getReceiver()).setMsg(priChat.getMsg()).build()).build();
            //通知数据库服务器保存私聊数据
            DbClientHandler.getDbServerCtx().writeAndFlush(sendPriMsg);
        }
        System.out.println(priChat.getSenderId()+"[私聊]:" +priChat.getMsg());
    }



    public void savePriChat(DbProto.Msg msg){
        Channel receiverCtx = PlayerCache.getInstance().getPlayer(msg.getChatMsg().getReceiverId()).getChannel();
        ChatProto.Msg priMsg = ChatProto.Msg.newBuilder().setMsgType(ChatProto.Msg.MsgType.priChat)
                .setRespChat(ChatProto.RespChat.newBuilder().setSender(msg.getChatMsg().getSenderName())
                        .setMsg(msg.getChatMsg().getMsg()).setTime(msg.getChatMsg().getTime()).build()).build();
        receiverCtx.writeAndFlush(priMsg);
    }
}
